<?php

namespace Modules\Visitor\Entities;

use Modules\Core\Entities\BaseEntity as Model;

// use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

use Zhuzhichao\IpLocationZh\Ip as IP;

class Visitor extends Model
{
    protected $guarded = [];
    protected $table = 'visitors';
    // protected $collection = 'visitors';
    // protected $connection = 'visitor';
    // public $timestamps = false;
    // protected $dates = ['visit_at'];

    static public $resourceName = '访客记录';

    protected $casts = [
        'origin' => 'array',
        'user' => 'array',
        'tenant' => 'array',
        'wechat' => 'array',
        'page' => 'array',
        'client' => 'array',
        'device' => 'array',
        'platform' => 'array',
        'browser' => 'array',
        'share_by' => 'array',
    ];    

    // protected $page = 1;
    // protected $perPage = 20;
    // protected $itemTotal = 0;
    // protected $orderBy = ['id', 'desc'];
    // protected $only = false;
    // public $builder = null;
    // public $list = false;

    public $titleMap = [
        'home' => '首页',
        'box_index' => '盲盒首页',
        'shop_index'  => '商城首页',
        'box_detail' => '抽盒页',
        'small_box_detail' => '开盒页',
        'product_detail' =>  '商品详情页',
        'category' => '分类页',
        'search' => '搜索页',
        'activity_index' => '活动首页',
        'cart' => '购物车',
        'login' => '登陆页',
        'center'  =>  '个人中心',
        'coupon_detail' => '优惠券领取页',
        'activity_detail' => '活动详情页',
        'day_task' => '每日任务'
    ];

    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    public function mapTitle($key)
    {
        return @v($this->titleMap[$key], '未知页面');
    }

    public function scopeApp($query, $app)
    {
        return $query->where('app', $app);
    }

    // 搜索
    public function scopeSearch($query, $key)
    {
        return $query->whereHasIn('user', function ($q) use ($key) {
            return $q->where('phone', $key)->orWhere('name', 'like', '%' . $key . '%');
        });
    }

    public function init($ip)
    {
        $city = Ip::find($ip);

        $this->uuid = uniqid();

        $this->ip = $ip;
        $this->country = @$city[0];
        $this->province = @$city[1];
        $this->city = @$city[2];

        $this->user = null;
        $this->wechat = null;
        $this->origin = null;
        $this->share_by = null;
        $this->page = null;

        $this->visit_at = now();

        return $this;
    }

    public function createAll()
    {
        $this->save();
    }

    static public function deleteLeftFor($leftTotal)
    {
        $item = Visitor::orderBy('id', 'desc')->skip($leftTotal)->first();

        if ($item) {
            Visitor::where('id', '<',  $item->id)->forceDelete();
        }
    }
}
